package com.cabinet.ui;

import com.cabinet.Device;
import com.cabinet.PortChangeListener;
import com.cabinet.SendReceiveThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: lesya
 * Date: 1/18/14
 * Time: 11:50 AM
 * To change this template use File | Settings | File Templates.
 */
public class DebugPortDialog extends JDialog{
  List<JLabel> outLabs = new ArrayList<>();
  List<JLabel> inLabs = new ArrayList<>();

  public DebugPortDialog(Frame owner, String title) {
    super(owner, title);

    List<Device> allDev = Device.all();
    setLayout(new GridLayout(allDev.size(), 3, 8, 1));
    for( Device d : allDev){
      add(new JLabel(d.getShortName()));
      JLabel lout = new JLabel("99999999");
      add(lout);
      outLabs.add(lout);
      if( Device.isStudent(d.getId()) ){
        JLabel lin = new JLabel("99999999");
        inLabs.add(lin);
        add(lin);
      }else{
        add(new JLabel(""));
      }
    }

    SendReceiveThread.INST.addPortChangeListener(new PortChangeListener() {
      @Override
      public void change(final byte[] pout, final byte[] pin) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            changeNotify(pout, pin);
          }
        });
      }
    });

//    Timer timer = new Timer(500, new ActionListener() {
//      @Override
//      public void actionPerformed(ActionEvent actionEvent) {
//        if( isVisible() ){
//          setVisible(true); // to-top
//        }
//      }
//    });
   // timer.setInitialDelay(500);
  //  timer.start();
//    addWindowListener(new WindowAdapter() {
//      @Override
//      public void windowDeactivated(WindowEvent e) {
//        setVisible(true);
//      }
//    });
  }

  void changeNotify(byte[] pout, byte[] pin){
    for( int i=0; i<pout.length; i++ ){
      String v = SendReceiveThread.binaryVal(pout[i]);
      if( !v.equals(outLabs.get(i).getText()) ){
        outLabs.get(i).setText(v);
      }
    }

    if( pin!=null ){
      for( int i=0; i<pin.length; i++ ){
        String v = SendReceiveThread.binaryVal(pin[i]);
        if( !v.equals(inLabs.get(i).getText()) ){
          inLabs.get(i).setText(v);
        }
      }
    }

    if( isVisible() ){
     // setVisible(true); // to-top

    }

  }
}
